var formValidator = function(frmId, rules, messages) {
	this.frmId = frmId;
	this.rules = rules;
	this.messages = messages;
};

formValidator.prototype.validation = function(){
	var rtnValue = true;
	var rules = this.rules;
	for(i in rules){
		var ele = rules[i];
		
		rtnValue = this.formJsonParse(ele, i);
		if(!rtnValue) break;
	}	
	
	return rtnValue;
};

formValidator.prototype.formJsonParse = function(obj, pkey){
	var rtnValue = true;
	
	for(i in obj){
		var ele = obj[i];
		
		if(typeof(ele) === "object"){
			rtnValue = this.formJsonParse(ele, i);
		}else{
			var jsonQuery = new Object();
			jsonQuery["query"] = "this.messages."+pkey+"."+i;
			jsonQuery["pkey"] = pkey;
			jsonQuery["key"] = i;
			jsonQuery["value"] = obj[i];
			
			rtnValue = this.comment(jsonQuery);
		}
		
		if(!rtnValue) break;
	}
	
	return rtnValue;
};

formValidator.prototype.comment = function(jsonQuery){
	var rtnValue = true;
	var query = jsonQuery.query;
	var pkey = jsonQuery["pkey"];
	var key = jsonQuery["key"];
	var value = jsonQuery["value"];
	var obj = $("#"+this.frmId + " #"+pkey);
	var msg = eval(query);
	
	if(key == "required"){
		if(typeof value === "boolean" && !value){
		}else{ if($(obj).val().length == 0) rtnValue = this.msgContainer(msg, $(obj));
		}			
	}else if(key == "minlength"){ if($(obj).val().length < value) rtnValue = this.msgContainer(msg, $(obj));			
	}else if(key == "maxlength"){ if($(obj).val().length > value) rtnValue = this.msgContainer(msg, $(obj));
	}else if(key == "expression"){
		var exp = new RegExp(eval(value));
		if(!exp.test($(obj).val()))  rtnValue = this.msgContainer(msg, $(obj));
	}

	return rtnValue;
};

formValidator.prototype.msgContainer = function(msg, obj){
	var rtnValue = false;		
	if(msg == null || msg == "undefined") msg = "Unknown internal error!!! \nThe error message is nothing.";
	
	alert(msg);
	$(obj).focus();
	return rtnValue;
};